package server

import (
	"context"
	"net/http"

	"alolang.org.cn/api/server/config"
	"alolang.org.cn/api/server/log"
	"alolang.org.cn/api/server/model"
	"alolang.org.cn/api/server/router"
)

var Server *http.Server

// Run 运行server
func Run() {
	log.LogInit()

	// 验证运行配置
	if err := config.Server.Validate(); err != nil {
		panic("Validate config error: " + err.Error())
	}
	log.Logger.WithFields(map[string]interface{}{
		"log_level":    config.Server.LogLevel,
		"http.address": config.Server.HTTP.Address,
	}).Info("API Server最终运行配置\n")

	// 初始化数据库及Redis
	model.DBInit()
	defer model.DBClose()

	// 启动HTTP服务
	Server = &http.Server{
		Addr:    config.Server.HTTP.Address,
		Handler: router.GinEngine(),
	}
	if err := Server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
		log.Logger.Errorf("HTTP server listen and serve error: %s", err)
	}
}

func Shutdown(ctx context.Context) {
	if err := Server.Shutdown(ctx); err != nil {
		log.Logger.Errorf("Server shutdown error: ", err)
	}
}
